/*
 * @Descripttion: http请求封装
 * @Author: whl
 * @Date: 2022-06-29 10:27:15
 * @LastEditors: whl
 * @LastEditTime: 2022-07-01 11:51:36
 */

import axios from 'axios'
import Vue from 'vue'
import Cookie from '@/js/cookie'

let axiosBaseURL = process.env.NODE_ENV === 'development' ? '测试环境的api请求的url' : '正式环境的api请求的url'
let requestIndex = 0
axios.interceptors.request.use(config => { // 配置发送请求的信息
  let token = ''
  if (process.env.NODE_ENV === 'development') {
    // 测试环境
    token = Cookie.getCookie('token')
  } else {
    token = Cookie.getCookie('token')
  }
  if (token) {
    // 添加headers
    config.headers.token = `${token}`
    config.headers['Content-Type'] = 'application/json'
  }
  // 队列不展示loading
  if (!config.url.split('/').includes('wordJobs')) {
    startLoading()
  }
  return config
}, error => {
  return Promise.reject(error)
})

// 添加响应拦截器
axios.interceptors.response.use(response => { // 配置请求回来的信息
  // 自己配置了一个alwaysShowLoading控制展示loading图 true：loading图要手动关闭，不存在或者false:loading自动会消失
  if (!response.config.alwaysShowLoading) {
    closeLoading()
  }
  // 错误统一处理
  if (response.data.resultCode && response.data.resultCode !== 0) {
    // 其他地方登录
    let jumpUrl = '/login'
    // TODO:对应做修改
    if (response.data.errorCode === 20000011) {
      Vue.$alert({
        subMessage: response.data.message,
        hideCancel: true
      }, () => {
        window.location.href = jumpUrl
      }, () => {
        window.location.href = jumpUrl
      })
    } else {
      Vue.$Message.error(response.data.message)
    }
    return Promise.reject(response)
  }
  return response
}, error => {
  // 对响应错误做点什么
  if (requestIndex < 1) {
  }
  closeLoading()
  if (String(error) === 'Error: Network Error') {
    // console.error('网络异常')
  }
  return Promise.reject(error)
})

function startLoading () {
  console.log('loading...')
  requestIndex++
}

function closeLoading () {
  if (requestIndex === 0) { return false }
  requestIndex--
  if (requestIndex === 0) {
    console.log('close')
  }
}

// 封装get方法
export function httpGet (url, params, config) {
  return new Promise((resolve, reject) => {
    axios.get(url, { 'params': params }, config).then(res => {
      resolve(res.data)
    }).catch(err => {
      reject(err.data)
    })
  })
}
// 封装post方法
export function httpPost (url, params, config) {
  return new Promise((resolve, reject) => {
    axios.post(url, params, config).then(res => {
      resolve(res.data)
    }).catch(err => {
      reject(err.data)
    })
  })
}
// delete
export function httpDelete (url, params, config) {
  return new Promise((resolve, reject) => {
    axios.delete(url, {data: params}, config).then(res => {
      resolve(res.data)
    }).catch(err => {
      reject(err.data)
    })
  })
}
// put
export function httpPut (url, params, config) {
  return new Promise((resolve, reject) => {
    axios.put(url, params, config).then(res => {
      resolve(res.data)
    }).catch(err => {
      reject(err.data)
    })
  })
}

export function httpRequest ({ method, url, data, config }) {
  axios.defaults.baseURL = axiosBaseURL
  if (method === 'get') {
    return httpGet(url, data, config)
  } else if (method === 'post') {
    return httpPost(url, data, config)
  } else if (method === 'delete') {
    return httpDelete(url, data, config)
  } else if (method === 'put') {
    return httpPut(url, data, config)
  }
}
